package com.xian.ai.code.config;

/*
  @ClassName CosClientConfig
 * @Description TODO
 * @Author Zhangxn
 * @Version 1.0
 */


import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;




@Configuration
@ConfigurationProperties(prefix = "cos.client")
@Data
@Slf4j
public class CosClientConfig {

    /**
     * 域名
     */
    private String host;

    /**
     * secretId
     */
    private String secretId;

    /**
     * 密钥（注意不要泄露）
     */
    private String secretKey;

    /**
     * 区域
     */
    private String region;

    /**
     * 桶名
     */
    private String bucket;

    @Bean(destroyMethod = "shutdown")
    public COSClient cosClient() {
        // 检查必要配置是否存在
        if (secretId == null || secretKey == null || region == null || bucket == null) {
            log.warn("COS client configuration is incomplete. Please check your configuration.");
            return null;
        }
        
        try {
            // 初始化用户身份信息(secretId, secretKey)
            COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
            // 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            // 生成cos客户端
            COSClient cosClient = new COSClient(cred, clientConfig);
            log.info("COS client initialized successfully.");
            return cosClient;
        } catch (Exception e) {
            log.error("Failed to initialize COS client: {}", e.getMessage(), e);
            return null;
        }
    }
}
